/**
 * 地图，由宽度一致(128px*?)的障碍物组合而成
 * 障碍物ID:
 *  0 角色可以在上面跑的障碍物，水平线为360px
 *  n 同0，水平线为360-50*n
 */

import {Sprite, Text, stage} from '../LayaLib.js'
import {Block, WIDTH as BLOCK_WIDTH} from './Block.js'
import role from '../Role.js'

/**一屏障碍的数量 */
var BLOCK_NUMBER = 10
/**地图移动的速度 */
var speed = 5
/**经过的障碍数量，用于计算距离 */
var distance = 0
/**上一块障碍的序号 */
var lastBlock = -1

function getBlockType() {
    var r = Math.random()
    if(r < 0.6) return 1
    else if(r < 0.8) return 2
    else if(r < 0.95) return 3
    else if(r < 1) return 0
}

var map = new Sprite()
stage.addChild(map)
//初始化两屏的障碍数量
for(var i = 0; i < BLOCK_NUMBER * 2; i++) {
    var b = new Block(1)
    b.x = i * BLOCK_WIDTH
    map.addChild(b)
}
map.cacheAsBitmap = true
map.staticCache = true

// var speedText = new Text()
// speedText.text = '速  度：' + speed
// stage.addChild(speedText)

var lastDistanceText = new Text()
lastDistanceText.text = '上次成绩：0'
lastDistanceText.y = 20
stage.addChild(lastDistanceText)

var distanceText = new Text()
distanceText.text = '成  绩：0'
distanceText.y = 5
stage.addChild(distanceText)

lastDistanceText.font = distanceText.font = 'Microsoft YaHei'
// lastDistanceText.color = distanceText.color = speedText.color = '#ffffff'
// lastDistanceText.fontSize = distanceText.fontSize = speedText.fontSize = 24

stage.on('GAME_OVER', stage, ()=> {
    map.clearTimer(map, move)
})

function move() {
    map.x -= speed
    if(map.x <= -BLOCK_WIDTH * BLOCK_NUMBER) {
        //后一半的障碍替换到前一半，然后再随机生成地图
        for(var i = 0; i < BLOCK_NUMBER; i++) {
            var fore = map.getChildAt(i)
            var hind = map.getChildAt(i + BLOCK_NUMBER)
            fore.update(hind.type)
            hind.update(getBlockType())
        }
        map.reCache()
        map.x += BLOCK_WIDTH * BLOCK_NUMBER
    }else {
        var j = Math.floor((role.x - map.x) / BLOCK_WIDTH)
        var b = map.getChildAt(j)
        b.test(role, b.x + map.x)
        if(j != lastBlock) {
            lastBlock = j
            distance++
            distanceText.text = '成  绩：' + distance
            // if(distance % (BLOCK_NUMBER * 4) === 0 && speed < 5) {
            //     //速度增加
            //     speed++
            //     role.raiseSpeed()
            //     speedText.text = '速  度：' + speed
            // }
        }
    }
}

export function start() {

    for(var i = BLOCK_NUMBER * 2 - 1; i >= 0; i--) {
        map.getChildAt(i).update(1)
    }
    lastDistanceText.text = '上次成绩：' + distance
    // speedText.text = '速  度：4'
    distanceText.text = '成  绩：0'

    speed = 4
    distance = 0
    lastBlock = -1
    
    map.x = 0
    map.timerLoop(15, map, move)
}

